package com.demo.zhou.sniper.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.demo.zhou.sniper.R;
import com.demo.zhou.sniper.adapter.CustomArrayAdapter;
import com.demo.zhou.sniper.adapter.HorizonListviewAdapter;
import com.demo.zhou.sniper.application.MyApplication;
import com.demo.zhou.sniper.gen.ColorTableDao;
import com.demo.zhou.sniper.gen.DaoSession;
import com.demo.zhou.sniper.module.ColorTable;
import com.demo.zhou.sniper.util.HorizontalListView;
import com.demo.zhou.sniper.util.MyListview;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by zhou on 2017/9/16.
 */

public class ColorTableActivity extends BaseActivity implements View.OnClickListener {

    static int COLOR_COUNT = 150;

    private HorizontalListView color_mHlvSimpleList;
    private List<String> cTableList1 = new ArrayList<>();
    CustomArrayAdapter adapter;
    private Button color_bt_table, color_bt_flush;
    private TextView color_tv_add;
    private HorizonListviewAdapter[] horizonListviewAdapters;
    DaoSession daoSession;
    ColorTableDao colorTableDao;
    private List<ColorTable> cTableList = new ArrayList<>();
    private MyListview mListView1;
    private MyAdapter myadapter;
    static ColorTable colorTable;

    @Override
    protected int getContentView() {
        return R.layout.activity_colortable_layout;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //从存储中获取得到色表，若无，随机生成一个数据源
        //根据所选中的色表，点击保存时进行保存
        setTitle("色表");
        intoView();
    }

    private void intoView() {
        //初始化控件，并对列表赋值color_mHlvSimpleList
        color_mHlvSimpleList = findViewById(R.id.color_mHlvSimpleList);
        color_bt_table = findViewById(R.id.color_bt_table);
        color_bt_flush = findViewById(R.id.color_bt_flush);
        color_tv_add = findViewById(R.id.color_tv_add);
        mListView1 = findViewById(R.id.mylist);
        daoSession = ((MyApplication) getApplication()).getDaoSession();
        colorTableDao = daoSession.getColorTableDao();
        refreshColorTable();
        mListView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cTableList1.clear();
                colorTable = cTableList.get(position);
                char[] cs = colorTable.getCt_centon().toCharArray();
                for (char c : cs) {
                    cTableList1.add(c + "");
                }
                color_tv_add.setText("更新色表\n" + colorTable.getId() + "*" + colorTable.getCt_type());
                adapter.notifyDataSetChanged();
            }
        });
        mListView1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int position, final long id) {
                // 定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
                androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(ColorTableActivity.this);
                builder.setMessage("是否要删除该色表?");
                builder.setTitle("提示");
                //添加AlertDialog.Builder对象的setPositiveButton()方法
                builder.setPositiveButton("删除", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        if (deleteColorTableData(position, cTableList.get(position).getId())) {

                            refreshColorTable();
                            Toast.makeText(ColorTableActivity.this, "删除成功！", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(ColorTableActivity.this, "删除失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                //添加AlertDialog.Builder对象的setNegativeButton()方法
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

                builder.create().show();
                return true;
            }
        });
        cTableList1.addAll(getTable());
        adapter = new CustomArrayAdapter(this, cTableList1);
        color_mHlvSimpleList.setAdapter(adapter);
        color_mHlvSimpleList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (cTableList1.get(position).equals("d")) {
                    cTableList1.set(position, "x");
                } else {
                    cTableList1.set(position, "d");
                }
                adapter.notifyDataSetChanged();

            }
        });
        color_bt_table.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == colorTable) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ColorTableActivity.this);
                    builder.setIcon(android.R.drawable.alert_dark_frame);
                    builder.setTitle("请选择色表类型");
                    final String[] items = new String[]{"B", "L"};
                    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String str_content = "";
                            for (String str : cTableList1) {
                                str_content += str;
                            }
                            colorTable = new ColorTable(null, "1", items[which], str_content);
                            colorTableDao.insert(colorTable);
                            colorTable = null;
                            color_tv_add.setText("添加色表");

                            refreshColorTable();
                            Toast.makeText(ColorTableActivity.this, "色表保存成功！", Toast.LENGTH_SHORT).show();

                            dialog.dismiss();

                        }
                    });
                    builder.show();
                } else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ColorTableActivity.this);
                    builder.setIcon(android.R.drawable.alert_dark_frame);
                    builder.setTitle("请选择色表类型");
                    final String[] items = new String[]{"B", "L"};
                    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String str_content = "";
                            for (String str : cTableList1) {
                                str_content += str;
                            }
                            colorTable.setCt_centon(str_content);
                            colorTable.setCt_type(items[which]);
                            colorTableDao.update(colorTable);
                            colorTable = null;
                            color_tv_add.setText("添加色表");
                            refreshColorTable();
                            Toast.makeText(ColorTableActivity.this, "更新成功，请按「刷新」按钮刷新！", Toast.LENGTH_LONG).show();
                            dialog.dismiss();

                        }
                    });
                    builder.show();

                }

            }
        });
        color_bt_flush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onCreate(null);
            }
        });
    }

    private void refreshColorTable() {
        cTableList.clear();
        horizonListviewAdapters = null;

        cTableList.addAll(colorTableDao.loadAll());
        if (!cTableList.isEmpty() && cTableList.size() > 0) {
            horizonListviewAdapters = new HorizonListviewAdapter[cTableList.size()];
            for (int i = 0; i < cTableList.size(); i++) {
                List<String> tables = new ArrayList();
                char[] cs = cTableList.get(i).getCt_centon().toCharArray();
                for (char c : cs) {
                    tables.add(c + "");
                }
                horizonListviewAdapters[i] = new HorizonListviewAdapter(ColorTableActivity.this, tables);
            }
            myadapter = new MyAdapter(cTableList, horizonListviewAdapters);
            mListView1.setAdapter(myadapter);
            myadapter.notifyDataSetChanged();
        }
    }


    private HorizonListviewAdapter[] delAnyPosition(HorizonListviewAdapter[] arr, int position) {
        //判断是否合法
        if (position >= arr.length || position < 0) {
            return null;
        }
        HorizonListviewAdapter[] res = new HorizonListviewAdapter[arr.length - 1];
        for (int i = 0; i < res.length; i++) {
            if (i < position) {
                res[i] = arr[i];
            } else {
                res[i] = arr[i + 1];
            }
        }
        return res;
    }


    public boolean deleteColorTableData(int position, long id) {
        Log.e("dly", "删除：id= " + id);

        try {
            if (colorTableDao == null) colorTableDao = daoSession.getColorTableDao();
//            cTableList = colorTableDao.loadAll();
            ColorTable colorTable = colorTableDao.load(id);
            Log.e("dly", "删除：colorTable= " + colorTable);
            Log.e("dly", "删除：colorTable= " + colorTable.getCt_id());
            Log.e("dly", "删除：colorTable= " + colorTable.getCt_centon());

            // 删除数据库数据
            colorTableDao.delete(colorTable);
        } catch (Throwable t) {
            t.printStackTrace();
            return false;
        }

        return true;
    }

    public List<String> getTable() {
        cTableList1.clear();
        List<String> tableList = new ArrayList<>();
        for (int i = 0; i < COLOR_COUNT; i++) {
            tableList.add(new Random().nextInt(10) + 1 >= 5 ? "d" : "x");
        }
        return tableList;
    }

    @Override
    public void onClick(View v) {

        soveColorData();

    }


    public void soveColorData() {

    }

    public class MyAdapter extends BaseAdapter {

        private LayoutInflater inflater = null;
        private List<ColorTable> data;
        private HorizonListviewAdapter[] adapter;

        public MyAdapter(List<ColorTable> data, HorizonListviewAdapter[] adapter) {
            this.adapter = adapter;
            this.data = data;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public HorizonListviewAdapter getAdapter(int position) {
            return adapter[position];
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            inflater = LayoutInflater.from(getApplicationContext());
            convertView = inflater.inflate(R.layout.item_goods, null);
            TextView name = convertView.findViewById(R.id.tv_name);
            name.setText(data.get(position).getId() + "*" + data.get(position).getCt_type());
            HorizontalListView mListView = (HorizontalListView) convertView.findViewById(R.id.horizontal_listview);
            mListView.setAdapter(adapter[position]);
            return convertView;
        }

        @Override
        public void notifyDataSetChanged() {
            super.notifyDataSetChanged();
            for (HorizonListviewAdapter ad : adapter) {
                ad.notifyDataSetChanged();
            }
        }
    }
}
